 

package com.zdkj.subway.stm.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zdkj.admin.api.entity.SysDictItem;
import com.zdkj.common.core.constant.CommonConstants;
import com.zdkj.common.core.constant.SecurityConstants;
import com.zdkj.common.core.util.R;
import com.zdkj.common.log.annotation.SysLog;
import com.zdkj.common.security.service.PigxUser;
import com.zdkj.common.security.util.ObjectUtils;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.stm.constant.StmConstans;
import com.zdkj.subway.stm.constant.StmTableCommon;
import com.zdkj.subway.stm.dto.in.QueryContionDTO;
import com.zdkj.subway.stm.dto.in.SwStInternetTicketDTO;
import com.zdkj.subway.stm.dto.in.SwStInternetTicketDataDTO;
import com.zdkj.subway.stm.dto.in.SwStReportErrorAlterApplyDTO;
import com.zdkj.subway.stm.entity.SwStInternetTicketEquipment;
import com.zdkj.subway.stm.entity.SwStInternetTicketEquipmentDetails;
import com.zdkj.subway.stm.entity.SwStmStationDataEntryLog;
import com.zdkj.subway.stm.fegin.SubwayCheckService;
import com.zdkj.subway.stm.fegin.SystemUserService;
import com.zdkj.subway.stm.mapper.SwAuInternetTicketEquipmentMapper;
import com.zdkj.subway.stm.service.SwStInternetTicketEquipmentDetailsService;
import com.zdkj.subway.stm.service.SwStInternetTicketEquipmentService;
import com.zdkj.subway.stm.service.SwStmStationDataEntryLogService;
import com.zdkj.subway.stm.util.DateUtilStm;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 互联网售票机主表
 *
 * @author songtuo
 * @date 2020-03-07 20:14:22
 */
@RestController
@AllArgsConstructor
@RequestMapping("/swstinternetticketequipment" )
@Api(value = "swstinternetticketequipment", tags = "互联网售票机主表管理")
@Slf4j
public class SwStInternetTicketEquipmentController {

    private final  SwStInternetTicketEquipmentService swStInternetTicketEquipmentService;

    private final SwStInternetTicketEquipmentDetailsService swStInternetTicketEquipmentDetailsService;

    private final SystemUserService systemUserService;

    private final SubwayCheckService subwayCheckService;

    private final SwStmStationDataEntryLogService swStmStationDataEntryLogService;

    private final SwAuInternetTicketEquipmentMapper swAuInternetTicketEquipmentMapper;

    /**
     * 分页查询
     * @param page 分页对象
     * @param swStInternetTicketEquipment 互联网售票机主表
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page" )
    public R getSwStInternetTicketEquipmentPage(Page page, SwStInternetTicketEquipmentDetails swStInternetTicketEquipment, QueryContionDTO queryContionDTO) {
        QueryWrapper<SwStInternetTicketEquipmentDetails> queryWrapper = Wrappers.query(swStInternetTicketEquipment);
        SwStInternetTicketEquipmentDetails swStInternetTicketEquipmentObj = ObjectUtils.getDefaultObj(SwStInternetTicketEquipmentDetails.class);
        swStInternetTicketEquipment.setLineCode(swStInternetTicketEquipmentObj.getLineCode());
        swStInternetTicketEquipment.setStationCode(swStInternetTicketEquipmentObj.getStationCode());
        queryWrapper.orderByDesc("START_TIME");
        return R.ok(swStInternetTicketEquipmentDetailsService.page(page, queryWrapper));
    }


    /**
     * 通过id查询互联网售票机主表
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}" )
    public R getById(@PathVariable("id" ) Integer id) {
        return R.ok(swStInternetTicketEquipmentService.getById(id));
    }

    /**
     * 新增互联网售票机主表
     * @param swStInternetTicketDataDto 互联网售票机主表
     * @return R
     */
    @ApiOperation(value = "新增互联网售票机主表", notes = "新增互联网售票机主表")
    @SysLog("新增互联网售票机主表" )
    @PostMapping
    @PreAuthorize("@pms.hasPermission('swstinternetticketequipment_add')" )
    public R save(@RequestBody SwStInternetTicketDataDTO swStInternetTicketDataDto) {
        List<SwStInternetTicketEquipmentDetails> sw = swStInternetTicketDataDto.getSwStInternetTicketEquipmentDetailsList();
        if (CollectionUtils.isNotEmpty(sw)) {
            Map<String, List<SwStInternetTicketEquipmentDetails>> countMap = sw.stream().collect(Collectors.groupingBy(swKey -> swKey.getEquipmentCode()));
            Set<String> codeSet = countMap.keySet();
            for (String epCode : codeSet) {
                LambdaUpdateWrapper<SwStInternetTicketEquipmentDetails> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                lambdaUpdateWrapper.eq(SwStInternetTicketEquipmentDetails::getLineCode, SecurityUtils.getUser().getLineCode())
                        .eq(SwStInternetTicketEquipmentDetails::getStationCode, SecurityUtils.getUser().getStationCode())
                        .eq(SwStInternetTicketEquipmentDetails::getRevenueDate, swStInternetTicketDataDto.getRevenueDate())
                        .eq(SwStInternetTicketEquipmentDetails::getEquipmentCode, epCode);
                SwStInternetTicketEquipmentDetails ited = swStInternetTicketEquipmentDetailsService.getOne(lambdaUpdateWrapper);
                SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
                String sDate=sdf.format(swStInternetTicketDataDto.getRevenueDate());
                if(ited!=null){
                    throw new RuntimeException("请检查该设备编号为"+epCode+"在" + sDate + "的数据已存在,请勿重复添加！");
                }
            }
        }
        List<SwStInternetTicketEquipmentDetails> SwStInternetTicketEquipmentList = new ArrayList<>();
        swStInternetTicketDataDto.setLineCode(SecurityUtils.getUser().getLineCode());
        swStInternetTicketDataDto.setStationCode(SecurityUtils.getUser().getStationCode());
        swStInternetTicketDataDto.setRemark(swStInternetTicketDataDto.getRemark());
        swStInternetTicketDataDto.getSwStInternetTicketEquipmentDetailsList().forEach(item -> {
            SwStInternetTicketEquipmentDetails defaultObj = ObjectUtils.getDefaultObj(SwStInternetTicketEquipmentDetails.class);
            BeanUtils.copyProperties(item, defaultObj);
            BeanUtils.copyProperties(swStInternetTicketDataDto, defaultObj);
            SwStInternetTicketEquipmentList.add(defaultObj);
        });
        return R.ok(swStInternetTicketEquipmentDetailsService.saveBatch(SwStInternetTicketEquipmentList));
        //return R.ok(swStInternetTicketEquipmentService.saveSwStInternetTicketData(swStInternetTicketDataDto));
    }

    /**
     * 修改互联网售票机主表
     * @param swStInternetTicketEquipmentDetails 互联网售票机主表
     * @return R
     */
    @ApiOperation(value = "修改互联网售票机主表", notes = "修改互联网售票机主表")
    @SysLog("修改互联网售票机主表" )
    @PutMapping
    @PreAuthorize("@pms.hasPermission('swstinternetticketequipment_edit')" )
    public R updateById(@RequestBody SwStInternetTicketEquipmentDetails swStInternetTicketEquipmentDetails) {
        SwStInternetTicketEquipmentDetails equipmentDetails = swStInternetTicketEquipmentDetailsService.getById(swStInternetTicketEquipmentDetails.getId());
        if(ObjectUtil.isNotEmpty(equipmentDetails)){
            Integer approvalStatus = equipmentDetails.getApprovalStatus();
            if(1 == approvalStatus){
                return R.failed(StmConstans.failedEdit);
            }
        }
        SimpleDateFormat dff = new SimpleDateFormat("yyyy-MM-dd");
        LambdaUpdateWrapper<SwStInternetTicketEquipmentDetails> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(SwStInternetTicketEquipmentDetails::getLineCode, swStInternetTicketEquipmentDetails.getLineCode())
                .eq(SwStInternetTicketEquipmentDetails::getStationCode, swStInternetTicketEquipmentDetails.getStationCode())
                .eq(SwStInternetTicketEquipmentDetails::getRevenueDate, swStInternetTicketEquipmentDetails.getRevenueDate())
                .eq(SwStInternetTicketEquipmentDetails::getEquipmentCode, swStInternetTicketEquipmentDetails.getEquipmentCode());
        SwStInternetTicketEquipmentDetails ited = swStInternetTicketEquipmentDetailsService.getOne(lambdaUpdateWrapper);
        if(ited!=null){
            if(!swStInternetTicketEquipmentDetails.getId().equals(ited.getId())){
                String sDate=dff.format(swStInternetTicketEquipmentDetails.getRevenueDate());
                throw new RuntimeException("请检查该设备编号为"+swStInternetTicketEquipmentDetails.getEquipmentCode()+"在" + sDate + "的数据已存在,请勿重复添加！");
            }
        }
        if("1".equals(swStInternetTicketEquipmentDetails.getReportModifyStatus())){
            //报表差错修改前先保存记录表
            PigxUser user = SecurityUtils.getUser();
            SwStmStationDataEntryLog swStmStationDataEntryLog = new SwStmStationDataEntryLog();
            swStmStationDataEntryLog.setRelationId(swStInternetTicketEquipmentDetails.getId());
            swStmStationDataEntryLog.setLogTableName(StmTableCommon.SW_ST_INTERNET_TICKET_EQUIPMENT_DETAILS);
            swStmStationDataEntryLog.setLogInfo(JSONObject.toJSONString(equipmentDetails));
            swStmStationDataEntryLog.setUpdateJobNo(user.getUserCode());
            swStmStationDataEntryLog.setUpdateJobName(user.getNikeName());
            swStmStationDataEntryLog.setUpdateTime(new Date());
            swStmStationDataEntryLogService.save(swStmStationDataEntryLog);
            //报表差错修改时更新审核模块互联网表
            SwStInternetTicketDTO swStInternetTicketDTO = new SwStInternetTicketDTO();
            swStInternetTicketDTO.setId(swStInternetTicketEquipmentDetails.getSwAuInternetTicketId());
            swStInternetTicketDTO.setLineCode(swStInternetTicketEquipmentDetails.getLineCode());
            swStInternetTicketDTO.setStationCode(swStInternetTicketEquipmentDetails.getStationCode());
            swStInternetTicketDTO.setTotalNumberSales(swStInternetTicketEquipmentDetails.getSaleNumber());
            swStInternetTicketDTO.setSubtotalTotal(swStInternetTicketEquipmentDetails.getTotalSaleAmount().multiply(new BigDecimal(100)));
            swStInternetTicketDTO.setRemark(swStInternetTicketEquipmentDetails.getRemark());
            swStInternetTicketDTO.setRevenueDate(DateUtilStm.dateToString(swStInternetTicketEquipmentDetails.getRevenueDate(),"yyyy-MM-dd"));
            subwayCheckService.invalidTicketEquipmentSave(SecurityConstants.FROM_IN,swStInternetTicketDTO);
        }
        boolean flag = swStInternetTicketEquipmentDetailsService.updateById(swStInternetTicketEquipmentDetails);
        if(flag && "1".equals(swStInternetTicketEquipmentDetails.getReportModifyStatus())){
            //修改互联网提交状态
            SwStInternetTicketEquipmentDetails sws = new SwStInternetTicketEquipmentDetails();
            sws.setApprovalStatus(1);
            sws.setReportModifyStatus("0");
            LambdaUpdateWrapper<SwStInternetTicketEquipmentDetails> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(SwStInternetTicketEquipmentDetails::getId, swStInternetTicketEquipmentDetails.getId());
            swStInternetTicketEquipmentDetailsService.update(sws,wrapper);
            //修改报表差错状态
            SwStReportErrorAlterApplyDTO swStReportErrorAlterApplyDTO = new SwStReportErrorAlterApplyDTO();
            swStReportErrorAlterApplyDTO.setLineCode(swStInternetTicketEquipmentDetails.getLineCode());
            swStReportErrorAlterApplyDTO.setStationCode(swStInternetTicketEquipmentDetails.getStationCode());
            swStReportErrorAlterApplyDTO.setReprotTime(DateUtilStm.dateToString(swStInternetTicketEquipmentDetails.getRevenueDate(),"yyyy-MM-dd"));
            swStReportErrorAlterApplyDTO.setEquipmentCode(swStInternetTicketEquipmentDetails.getEquipmentCode());
            subwayCheckService.updateXwReportInfos(SecurityConstants.FROM_IN,swStReportErrorAlterApplyDTO);
        }
        return R.ok(true);
    }


    /**
     * 通过id查询互联网售票机数据历史记录
     *
     * @param  id
     * @return R
     */
    @ApiOperation(value = "通过id查询互联网售票机数据历史记录", notes = "通过id查询互联网售票机数据历史记录")
    @GetMapping("getLogById/{id}")
    public R getLogById(@PathVariable("id") Integer id) {
        List<Object> LogInfoList = new ArrayList<>();
        List<SwStmStationDataEntryLog> swStmStationDataEntryLogs = swStmStationDataEntryLogService.getBaseMapper()
                .selectList(Wrappers.<SwStmStationDataEntryLog>lambdaQuery()
                        .eq(SwStmStationDataEntryLog::getRelationId, id)
                        .eq(SwStmStationDataEntryLog::getLogTableName, StmTableCommon.SW_ST_INTERNET_TICKET_EQUIPMENT_DETAILS));
        //返回json串
        if(CollectionUtil.isNotEmpty(swStmStationDataEntryLogs)){
            swStmStationDataEntryLogs.stream().forEach(x -> {
                JSONObject jsonObject = JSONObject.parseObject(x.getLogInfo());
                LogInfoList.add(jsonObject);
            });
        }
        //List<String> LogInfoList = swStmStationDataEntryLogs.stream().map(SwStmStationDataEntryLog::getLogInfo).collect(Collectors.toList());
        return R.ok(LogInfoList);
    }
    /**getSwAuInputInternetTicketEquipmentList
     * 通过id删除互联网售票机主表
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除互联网售票机主表", notes = "通过id删除互联网售票机主表")
    @SysLog("通过id删除互联网售票机主表" )
    @DeleteMapping("/{id}" )
    @PreAuthorize("@pms.hasPermission('swstinternetticketequipment_del')" )
    public R removeById(@PathVariable Integer id) {
        return R.ok(swStInternetTicketEquipmentService.deleteCascadeById(id));
    }

    /**
     * 查询互联网售票详情
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询互联网售票详情", notes = "通过id查询")
    @GetMapping("/details/{id}" )
    public R getSwStInternetTicketData(@PathVariable("id" ) Integer id) {
        return R.ok(swStInternetTicketEquipmentService.queryDetailsByid(id));
    }

    /**
     * 更改提交状态
     */
    @ApiOperation(value = "更改提交状态", notes = "更改提交状态")
    @PutMapping("/modify/approval/status")
    @PreAuthorize("@pms.hasPermission('swstinternetticketequipment_update_approval_status')" )
    public R updateApprovalStatus(@RequestParam("ids") List<Integer> ids, @RequestParam("status") String status) {
        return R.ok(swStInternetTicketEquipmentService.updateApprovalStatus(ids,status));
    }

    /**
     * 通过id批量删除互联网售票
     * @param idList id
     * @return R
     */
    @ApiOperation(value = "通过id批量删除互联网售票", notes = "通过id批量删除互联网售票")
    @SysLog("通过id批量删除互联网售票")
    @DeleteMapping("/batchDelete")
    @Transactional
    @PreAuthorize("@pms.hasPermission('swstinternetticketequipment_batch_del')")
    public R batchRemoveById(@RequestBody List<Integer> idList) {
        List<SwStInternetTicketEquipmentDetails> list = swStInternetTicketEquipmentDetailsService.list(new QueryWrapper<SwStInternetTicketEquipmentDetails>().lambda().in(SwStInternetTicketEquipmentDetails::getId, idList));
        List<Integer> deleteIds = list.stream().filter(x -> !x.getApprovalStatus().equals(CommonConstants.SUBMIT)).map(x -> x.getId()).collect(Collectors.toList());
        if(CollectionUtil.isEmpty(deleteIds)){
            return R.failed(StmConstans.failedDelete);
        }
        deleteIds.forEach(swStInternetTicketEquipmentDetailsService::removeById);
        //List<SwStInternetTicketEquipmentDetails> swStAuList = list.stream().filter(x -> x.getSwAuInternetTicketId()!=null).collect(Collectors.toList());
        return R.ok();
    }

    @ApiOperation(value = "导出互联网售票数据", notes = "导出互联网售票数据")
    @GetMapping("/export")
    public void export(Page page, SwStInternetTicketEquipment stInternetTicketEquipment, HttpServletResponse response) {
        List<SwStInternetTicketEquipment> records = swStInternetTicketEquipmentService.page(page, Wrappers.query(stInternetTicketEquipment)).getRecords();
        try {
            R<List<SysDictItem>> inputDataStatus = systemUserService.getDictByType(StmConstans.STM_INPUT_DATA_STATUS);
            List<SysDictItem> dictData = inputDataStatus.getData();
            if (CollectionUtil.isNotEmpty(records)) {
                Map<String, String> map = dictData.stream().collect(Collectors.toMap(SysDictItem::getValue, SysDictItem::getLabel));
                for (SwStInternetTicketEquipment record : records) {
                    record.setApprovalStatus(map.get(record.getApprovalStatus()));
                }
            }
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("日营销车票数据", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + System.currentTimeMillis() + ".xlsx");
            EasyExcel.write(response.getOutputStream(), SwStInternetTicketEquipment.class).
                    sheet("互联网售票数据数据").doWrite(records);
        } catch (IOException e) {
            log.error("导出互联网售票数据");
        }
    }
}
